from typing import List, Dict, Any, Optional, Tuple
from apps.models.models import Coach_Schedules, Coach
from apps.schemas.schemas import ScheduleCreateRequest, ScheduleUpdateRequest


async def get_all_schedules(page: int = 1, page_size: int = 10) -> Tuple[int, List[Dict[str, Any]]]:
    """
    获取所有教练排班列表（分页）
    :param page: 页码
    :param page_size: 每页数量
    :return: (总数, 排班列表)
    """
    # 计算偏移量
    offset = (page - 1) * page_size
    # 获取总数
    total = await Coach_Schedules.all().count()
    # 查询当前页的课程数据
    schedules = await Coach_Schedules.all().offset(offset).limit(page_size).values(
        "schedule_id",
        "coach_id_id",
        "day_of_week",
        "start_time",
        "end_time",
        "is_active"
    )

    # 处理外键字段名
    formatted_schedules = []
    for schedule in schedules:
        formatted_schedules.append({
            "schedule_id": schedule["schedule_id"],
            "coach_id": schedule["coach_id_id"],
            "day_of_week": schedule["day_of_week"],
            "start_time": schedule["start_time"],
            "end_time": schedule["end_time"],
            "is_active": schedule["is_active"]
        })

    return total, formatted_schedules


async def get_schedules_by_coach(coach_id: int) -> List[Dict[str, Any]]:
    """
    根据教练ID获取排班信息
    :param coach_id: 教练ID
    :return: 排班列表
    """
    schedules = await Coach_Schedules.filter(coach_id_id=coach_id).all()
    if not schedules:
        return []

    schedule_list = []
    for schedule in schedules:
        schedule_list.append({
            "schedule_id": schedule.schedule_id,
            "day_of_week": schedule.day_of_week,
            "coach_id": schedule.coach_id_id,
            "start_time": schedule.start_time,
            "end_time": schedule.end_time,
            "is_active": schedule.is_active
        })

    return schedule_list


async def get_schedules_by_coach_and_day(coach_id: int, day_of_week: str) -> List[Dict[str, Any]]:
    """
    根据教练ID和星期几获取排班信息
    :param coach_id: 教练ID
    :param day_of_week: 星期几
    :return: 排班列表
    """
    schedules = await Coach_Schedules.filter(coach_id_id=coach_id, day_of_week=day_of_week).all()
    if not schedules:
        return []

    schedule_list = []
    for schedule in schedules:
        schedule_list.append({
            "schedule_id": schedule.schedule_id,
            "day_of_week": schedule.day_of_week,
            "coach_id": schedule.coach_id_id,
            "start_time": schedule.start_time,
            "end_time": schedule.end_time,
            "is_active": schedule.is_active
        })

    return schedule_list


async def create_schedule(data: ScheduleCreateRequest) -> bool:
    """
    创建新的教练排班
    :param data: 排班创建请求数据
    :return: 创建是否成功
    """
    # 检查教练是否存在
    coach = await Coach.get_or_none(coach_id=data.coach_id)
    if not coach:
        raise ValueError("Coach not found")

    try:
        # 创建排班
        await Coach_Schedules.create(
            coach_id_id=coach.coach_id,
            day_of_week=data.day_of_week,
            start_time=data.start_time,
            end_time=data.end_time,
            is_active=data.is_active
        )
        return True
    except Exception as e:
        raise Exception(f"Error creating schedule: {str(e)}")


async def update_schedule(schedule_id: int, data: ScheduleUpdateRequest) -> bool:
    """
    更新教练排班
    :param schedule_id: 排班ID
    :param data: 排班更新请求数据
    :return: 更新是否成功
    """
    # 查询排班
    schedule = await Coach_Schedules.get_or_none(schedule_id=schedule_id)
    if not schedule:
        return False

    update_data = data.dict(exclude_unset=True)  # 只获取提供的字段

    # 更新排班表
    if any(k in update_data for k in ['day_of_week', 'start_time', 'end_time', 'is_active']):
        await schedule.update_from_dict({
            k: v for k, v in update_data.items()
            if k in ['day_of_week', 'start_time', 'end_time', 'is_active']
        })

    # 更新外键关系（如果提供了）
    if 'coach_id' in update_data:
        coach = await Coach.get_or_none(coach_id=update_data['coach_id'])
        if not coach:
            raise ValueError("Coach not found")
        schedule.coach_id_id = coach.coach_id

    await schedule.save()
    return True


async def delete_schedule(schedule_id: int) -> bool:
    """
    删除教练排班
    :param schedule_id: 排班ID
    :return: 删除是否成功
    """
    schedule = await Coach_Schedules.get_or_none(schedule_id=schedule_id)
    if not schedule:
        return False

    await schedule.delete()
    return True
